Skip to main content

CanActivate route guards

המשמעות של CanActivate היא הרשות לגלוש לעמוד. CanActivate מדבר על הרשאות.

נניח שיש לנו עמוד שאנחנו רוצים שרק ה-admin יגיע אליו, לפני שמאשרים את המעבר לעמוד אנחנו צריכים לאשר שהמשתמש הוא בעל הרשאה מתאימה להכנס לשם.

יצירת ה-guard:

ng g guard guards/auth

שלבים בעבודה עם guard:

  1. יצירת guard service.
  2. implements the guard interface.
  3. implement the method of the interface.
  4. החזרה true to navigate, false to block navigation.
  5. Add the service to the providers of the module.
  6. עכשיו אפשר להוסיף את ה-guard לנתיב המתאים.

CanActivate​

הפונקציה מחליטה אם נתיב יכול להיות מופעל על סמך תנאי מסויים.

קודם נכתוב את canActivate.

course.guard.js
export class CourseGuard implements CanActivate

הפונקציה canActivate מקבלת שני פרמטרים: ActivatedRouteSnapshot, RouterStateSnapshot ומחזירה ערך בוליאני.

כדי להפעיל את ה-guard אנחנו מוסיפים אותו לנתיב שבו רוצים אותו. כאן למשל תהיה הגבלה על מי שיכול להכנס לעמוד הקורסים.

app.module
{ path: 'courses', component: CoursesComponent, canActivate: [CourseGuard] },

אם יש לנו למשל שירות שאומר לנו מתי הגולש הוא login אפשר להשתמש בו ב-guard.

auth.service.ts
export class AuthService {
loggenIn: boolean = false;
login(){
this.loggenIn = true;
}
logout(){
this.loggenIn = false;
}
isAuthenticated(){
this.loggenIn;
}
}
course.guard.js
constructor(private authService: AuthService){}

canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

if(this.authService.isAuthenticated()){
return true
} else {
this.router.navigate(['']);
return false;
}
}

CanActivateChild Route guard​

אנחנו רוצים להגן גם על כל המסלולי child של מסלול מסויים בלי לפרט לכל אחד את ה-guard. נצטרך לממש את הפונקציה canActivateChild.

course.guard.js
export class CourseGuard implements CanActivate, CanActivateChild{
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
return this.canActivate(childRoute, state);
}
}

ולהוסיף את ה-guard למקום הנכון.

app.module
{ path: 'courses', canActivateChild: [CourseGuard], children: [
{ path: 'course/:id', component: CourseComponent }
]},